package edu.parq.uaa.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DB {

	private Connection connection;
	private PreparedStatement[] stmts;

	public DB() throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		connection = DriverManager.getConnection(Config.DB1_URL,
				Config.DB1_USERNAME, Config.DB1_PASSWORD);
		// connection.createStatement().executeUpdate("set names 'utf8'");
		stmts = new PreparedStatement[8];
		stmts[0] = connection
				.prepareStatement("insert into forum values (?,?,?,?,?,?,?,?,?,?,?,?)");
	
		stmts[1] = connection
		.prepareStatement("select content from forum;");

		stmts[2] = connection
		.prepareStatement("insert into dictionary (contents) values (?)");

		stmts[3] = connection
		.prepareStatement("select * from dictionary where contents=?;");

	}
	
	
	public void addData(String [] fields)throws Exception{
		stmts[0].clearParameters();
		
		for (int i=1;i<=fields.length;i++)
			this.setString(stmts[0], i, fields[i-1]);
			
		stmts[0].executeUpdate();
	}
	
	
	public ResultSet getData()throws Exception{
		stmts[1].clearParameters();
		return stmts[1].executeQuery();
	}

	
	public void addDataToDictionary(String word)throws Exception{
		if (getDictionaryEntry(word)!=-1)
			return;
		
		stmts[2].clearParameters();
		this.setString(stmts[2], 1, word);
		stmts[2].executeUpdate();
	}
	
	
	public long getDictionaryEntry(String word)throws Exception{
		stmts[3].clearParameters();
		this.setString(stmts[3], 1, word);
		ResultSet rset=stmts[3].executeQuery();
		if (rset.next()){
			return rset.getLong("wid");
		}
		return -1;
	}

	
	public void setString(PreparedStatement stmt,int index,String str)throws Exception{
		byte[] utf8Bytes = str.getBytes("UTF8");
	    str = new String(utf8Bytes, "UTF8");
	    str=str.replaceAll("'", "''");

	    stmt.setString(index, str);
	}

	public void close()throws Exception{
		this.connection.close();
	}
}
